/*
 * @lc app=leetcode.cn id=82 lang=cpp
 *
 * [82] 删除排序链表中的重复元素 II
 */

#include <limits.h>

#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        
        ListNode* dummyNode = new ListNode(0, head);    // 链表插入伪头部
        ListNode* currNode = dummyNode;                 // 遍历过程中的当前节点

        if (head == nullptr) return nullptr;
        
        // 遍历原链表，currNode 及之前的元素是删减后的链表
        while (currNode->next && currNode->next->next) {
            if (currNode->next->val == currNode->next->next->val) {
                int x = currNode->next->val;
                while (currNode->next && currNode->next->val == x) {
                    currNode->next = currNode->next->next;
                }
            } else {
                currNode = currNode->next;
            }
        }
        
        return dummyNode->next;
    }
};
// @lc code=end

